// routes/auth/login.js
const express = require('express');
const jwt = require('jsonwebtoken');
const pool = require('../../config/pool'); // 使用连接池
const router = express.Router();
const bcrypt = require('bcrypt');

// 用户登录接口
router.post('/', (req, res) => {
    const { username, password } = req.body;
    // 校验username和password存在且长度大于等于5位且不包含特殊字符
    if (!username || !password) {
        return res.json({
            code: 0,
            message: '用户名和密码不能为空',
            success: false
        });
    }
    if (username.length < 5 || password.length < 5) {
        return res.json({
            code: 0,
            message: '用户名和密码长度必须大于等于5位',
            success: false
        });
    }
    if (username.includes(' ') || password.includes(' ')) {
        return res.json({
            code: 0,
            message: '用户名和密码不能包含空格',
            success: false
        });
    }
    // 查询用户
    const query = 'SELECT * FROM users WHERE username = ?';
    pool.query(query, [username], async (err, results) => {
        if (err) {
            console.error('数据库错误:', err);
            return res.json({
                code: 0,
                message: '数据库错误',
                success: false
            });
        }
        if (results.length === 0) {
            return res.json({
                code: 0,
                message: '凭证无效',
                success: false
            });
        }

        const user = results[0];

        // 验证密码
        const isPasswordValid = await bcrypt.compare(password, user.password);
        if (!isPasswordValid) {
            return res.json({
                code: 0,
                message: '凭证无效',
                success: false
            });
        }
        // 生成 JWT
        const token = jwt.sign({ user_id: user.id, username: user.username, is_admin: user.is_admin }, process.env.JWT_SECRET, { expiresIn: '30d' });
        res.json({
            code: 1,
            message: '登录成功',
            success: true,
            data: {
                token: token
            }
        });
    });
});

module.exports = router;